package com.iikira.sendsms

import android.app.Activity
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.telephony.SmsManager
import android.view.View
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    val mainActivity = this

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        query_2082.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                mainActivity.sendSMS("2082")
            }
        })
        query_cxll.setOnClickListener {
            mainActivity.sendSMS(query_cxll.text.toString())
        }
    }


    fun sendSMS(text: String) {
        val SENT = "sms_sent"
        val manager = SmsManager.getSmsManagerForSubscriptionId(0)

        val pi = PendingIntent.getBroadcast(this, 0, Intent(SENT), 0)

        // 发送结果监听
        registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(p0: Context?, p1: Intent?) {
                when (resultCode) {
                    Activity.RESULT_OK -> {
                        toast("发送成功")
                    }
                    else -> {
                        var res = p1?.getStringExtra(SENT)
                        if (res == null) {
                            res = "发送失败"
                        }
                        toast(res)
                    }
                }
            }
        }, IntentFilter(SENT))

        // 发送短信
        manager.sendTextMessage("10010", null, text, pi, null)
    }

    fun toast(msg: String?) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
    }
}
